#include "udp_client.hpp"
#include "err.hpp"

#include <memory>

#include <cstring>

#include <sys/types.h> //mkfifo
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h> //unlink/open/dup2/close

using namespace my_client;

#define FNAME "Received"

static void usage(const char* port)
{
    std::cout<<"USAGE:\n\t"<<port<<" serverip serverport\n"<<std::endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::string ip = argv[1];
    //std::cout<<ip<<std::endl;

    const uint16_t port = atoi(argv[2]);
    //std::cout<<port<<std::endl;
    std::unique_ptr<Client> client(new Client(ip,port));

    int n = mkfifo(FNAME,0664);
    if(n == -1) { exit(-2); }

    int fd = open(FNAME,O_WRONLY | O_RDONLY); //打开管道 写入收到的群消息
    if(fd == -1) { exit(-3); }

    n = dup2(fd,1); //重定向到stdout
    if(n == -1) { exit(-4); }

    //client->InitClient();
    client->Start();

    close(fd); //关闭文件描述符
    unlink(FNAME); //删除文件

    return 0;
}